<template>
  <div class="myStore">
    <!-- 头部 -->
    <div class="nav">
      <div class="wrapper-nav">
        <div class="content style2-nav clearfix">
          <!-- 会员中心 -->
          <span
            class="link"
            :class="postData.type == 1 ? 'cur': ''"
            @click="handleClickHeader(1)">{{virtual_store_alias}}</span>
          <span
            v-if="is_dhs_delivery_open == 1"
            class="link"
            :class="postData.type == 2 ? 'cur': ''"
            @click="handleClickHeader(2)">实体库存</span>
        </div>
      </div>
    </div>
    
    
    <!-- 列表 -->
    <ul class="mlist-goods"
        v-show="list.length">
      <van-list v-model="loading"
                :finished="finished"
                :error.sync="error"
                error-text="请求失败，点击重新加载"
                finished-text=""
                @load="loadMore">
        <li v-for="(item, index) in list"
            :key="index"
            class="list-goods">
          <section class="store-pic"
                   @click="JumpUrl(item.link)">
            <img v-if="item.is_compress"
                 :src="item.pic_url+'180x180'">
            <img v-else
                 :src="item.pic_url">
          </section>
          <section class="store-info">
            <h3 @click="JumpUrl(item.link)">
              <span class="fontZiy" v-if="item.is_self_support == 1">自营</span>
              {{item.title}}
            </h3>
            <p class="j-sale">库存:
              <span class="stock-del">{{item.total_num}}</span>
            </p>
            <div class="store">
              <div class="store-pop"
                   @click="showStoreSku(index)">库存详情
                <em class="down-icon" :class="showSkuIndex == index ? 'up-icon': ''"></em>
              </div>
              <!-- 定制SN码 开始 -->
              <div class="store-pop store-sn"
                   v-if="postData.type == 2 && item_sn_code_dz && item.sn_code_list.length > 0"
                   @click="showStoreSn(index)">码存详情
                <em class="down-icon"></em>
              </div>
            </div>
            <!-- 定制SN码 结束 -->
          </section>
          <!-- 定制SN码 有sn的时候 定制开始 -->
          <div class="pop-content"
               v-show="showSnIndex == index">
            <div class="pop-content-detail"
                 v-for="(snItem,snIndex) in item.sn_code_list"
                 :key="snIndex">
              <div class="content-left content-left-code">
                <div class="text-con">SN码数:{{snItem.sn_code}}</div>
                <div class="text-con flex-content">
                  <div class="title">关联订单号:</div>
                  <div class="content">
                    <p v-for="(codeItem, codeIndex) in snItem.order_no_list" :key="codeIndex">{{codeItem}}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- 定制SN码 有sn的时候 定制结束 -->
          <!-- 商品sku选择 -->
          <!-- 有商品sku的时候 -->
          <div class="pop-content"
               v-if="item.sku_list.length"
               v-show="showSkuIndex == index">
            <div class="pop-content-detail"
                 v-for="(skuItem,skuIndex) in item.sku_list"
                 :key="skuIndex">
              <div class="content-left" :style="{'width':postData.type == 2?'100%':''}">
                <p class="pop-content-detail-sku"
                   :data-sku="skuItem.sku_id">{{skuItem.sku_name}}</p>
                <p class="text-con">库存:<span class="stock-del">{{skuItem.num}}</span></p>
              </div>
              <div v-if="postData.type == 1" class="content-right">
                <div class="add-cart">
                  <i class="md-min"
                     @click="mdMin(index,skuIndex)">
                     <img :src="minImg" alt="" width="11" height="2">
                  </i>
                  <input type="tel"
                         v-model="skuItem.checkNum"
                         class="md-text"
                         >
                  <i class="md-add"
                     @click="mdAdd(index,skuIndex)">
                     <img :src="addImg" alt="" width="11" height="11">
                  </i>
                  <i class="j-addCart"
                     @click="addCart(item.item_id,skuItem.sku_id,skuItem.sku_name,index,skuIndex)"
                     v-if="!lowerId"></i>
                </div>
                <div class="stroe-sku-btn">
                  <van-button
                    class="dhs-deposit"
                    v-if="is_dhs_allow_deposit=='1'&&is_virtualstock_to_deposit=='1'"
                    :data-virtual_id="skuItem.virtual_id"
                    @click="dhsDeposit(skuItem.virtual_id,index,skuIndex)"
                    color="#F30C23" plain hairline round type="primary">兑换{{deposit_alias}}</van-button>
                  
                  <van-button class="shipments" v-if="!lowerId" @click="OnBuy(item.item_id,skuItem.sku_id,skuItem.sku_name,index,skuIndex)" color="linear-gradient(to right, #F82337, #FF2D59)" round >立即发货</van-button>
                  <van-button class="shipments" v-if="is_yj_dz && lowerId" @click="sendVirtual(lowerId,item.item_id,skuItem.sku_id,skuItem.sku_name,index,skuIndex)" color="#F30C23" round >确定</van-button>
                </div>
              </div>
              <div v-if="postData.type == 2" class="content-right">
                <div class="add-cart">
                  <i class="md-min"
                     @click="mdMin(index,skuIndex)">
                     <img :src="minImg" alt="" width="11" height="2">
                  </i>
                  <input type="tel"
                         v-model="skuItem.checkNum"
                         class="md-text"
                         >
                  <i class="md-add"
                     @click="mdAdd(index,skuIndex, 1)">
                     <img :src="addImg" alt="" width="11" height="11">
                  </i>
                </div>
                <div class="stroe-sku-btn">
                  
                  <van-button class="shipments" @click="sendVirtualEntity(item.entity_id,item.item_id,skuItem.sku_id,skuItem.sku_name,index,skuIndex)" color="#F30C23" round >确定修改</van-button>
                </div>
              </div>
            </div>
          </div>
          <!-- 没有sku -->
          <div v-else
               class="pop-content"
               v-show="showSkuIndex == index">
            <div class="pop-content-detail">
              <div class="content-left" :style="{'width':postData.type == 2?'100%':''}">
                <div class="pop-content-detail-sku"
                     data-sku="">购买数量</div>
                <div class="text-con">实际库存:<span>{{item.total_num}}</span></div>
              </div>
              <div v-if="postData.type == 1" class="content-right">
                <div class="add-cart">
                  <i class="md-min"
                     @click="mdMin(index)">
                     <img :src="minImg" alt="" width="11" height="2">
                  </i>
                  <input type="tel"
                         v-model="item.checkNum"
                         class="md-text"
                         readonly>
                  <i class="md_add"
                     @click="mdAdd(index)">
                     <img :src="addImg" alt="" width="11" height="11">
                  </i>
                  <i class="j-addCart"
                     @click="addCart(item.item_id,'','',index)"></i>
                </div>
                <div class="
                     stroe-sku-btn">
                  <van-button
                    class="dhs-deposit"
                    v-if="is_dhs_allow_deposit=='1'&&is_virtualstock_to_deposit=='1'"
                    @click="dhsDeposit(item.virtual_id,index)"
                    color="#F30C23" plain hairline round type="primary">兑换{{deposit_alias}}</van-button>
                  <van-button class="shipments" @click="OnBuy(item.item_id,'','',index,skuIndex)"  color="linear-gradient(to right, #F82337, #FF2D59)" round >立即发货</van-button>
                </div>
              </div>
            </div>
          </div>
        </li>
      </van-list>
    </ul>
    <div v-show="!list.length && finished">
      <no-data :noData="noData"></no-data>
    </div>
  </div>
</template>

<script>
import Store from '@/utils/store'
import { isIOS } from '@/utils/validate'
import noData from '@/components/noData/index'
import Scroll from '@/components/scroll/index'
import { getMyStore, depositExchange, addCart } from '@/api/user/dhs/dhsApi'
import { sendVirtualPost, sendVirtualPostEntity } from '@/api/dz/dzApi.js'
import Vue from 'vue'
import { Dialog } from 'vant'
Vue.use(Dialog)

export default Vue.extend({
  components: {
    noData,
    Scroll
  },
  data() {
    return {
      show: '',
      addImg:'https://img.wifenxiao.com/h5-wfx/images/user/add-num.png',
      minImg:'https://img.wifenxiao.com/h5-wfx/images/user/min-num.png',
      finished: false,
      loading: false,
      error: false,
      noData: {
        text: '暂无库存',
        img: 'https://img.wifenxiao.com/h5-wfx/images/user/no_order_data.png',
        marginTop: '10em'
      },
      p: 2,
      showSkuIndex: -1,
      is_dhs_allow_deposit: '0',
      is_virtualstock_to_deposit: '0',
      is_dhs_delivery_open: '0',
      deposit_alias: '预存款',
      virtual_store_alias: '库存',
      list: [],
      num: 0,
      buyItemId: '',
      buyNum: 0,
      buySkuId: '',
      buySkuName: '',
      is_yj_dz: false,
      lowerId: '',
      postData: {
        type: 1
      },
      item_sn_code_dz: 0, // 定制SN
      showSnIndex: -1
    }
  },
  created() {
    this.init()
    this.is_dz()
  },
  mounted() {
    // TODO 小程序触底加载更多
    window.addEventListener('reachbottom', () => {
      this.loadMore()
    })
  },
  methods: {
    is_dz() {
      const shop = this.$route.query.sid
      const lowerId = this.$route.query.lowerId
      const is_yj_dz = this.$_shop('$_yj', shop)
      this.is_yj_dz = is_yj_dz
      if (this.is_yj_dz && lowerId) {
        this.lowerId = lowerId
      }
    },
    // 定制sn码
    showStoreSn(index) {
      if (this.showSnIndex == index) {
        this.showSnIndex = -1
      } else {
        this.showSnIndex = index
      }
      this.showSkuIndex = -1
    },
    init() {
      this.$loadingWrap.show()
      setTimeout(() => {
        this.$loadingWrap.close()
      }, 50000)
      const param = Object.assign({}, this.postData, true)
      getMyStore(param).then(res => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          this.is_dhs_allow_deposit = res.data.is_dhs_allow_deposit
          this.is_virtualstock_to_deposit = res.data.is_virtualstock_to_deposit
          this.deposit_alias = res.data.deposit_alias
          if (res.data.virtual_store_alias) {
            this.virtual_store_alias = res.data.virtual_store_alias
              wx.setNavigationBarTitle({
                title: this.virtual_store_alias
              })
          }
          this.is_dhs_delivery_open = res.data.is_dhs_delivery_open
          this.list = res.data.lists
          // 定制SN码
          this.item_sn_code_dz = res.data.open_sn_code ? res.data.open_sn_code : 0
          // 其它
          param.type == 1 ? this.noData.text = `暂无${this.virtual_store_alias}` : this.noData.text = `暂无实体库存`
        } else {
          this.$Error(res.msg)
        }
      })
    },
    // 点击头部tab
    handleClickHeader(type) {
      this.postData.type = type
      this.init()
    },
    // 显示隐藏
    showStoreSku(index) {
      if (this.showSkuIndex == index) {
        this.showSkuIndex = -1
      } else {
        this.showSkuIndex = index
      }
    },

    // 加数量
    mdAdd(index, skuIndex, entity) {
      if (skuIndex || skuIndex == 0) {
        const num = entity ? this.list[index].sku_list[skuIndex].num - 1 : this.list[index].sku_list[skuIndex].num
        if (this.list[index].sku_list[skuIndex].checkNum < num) {
          this.list[index].sku_list[skuIndex].checkNum++
        }
      } else {
        const totalNum = entity ? this.list[index].total_num - 1 : this.list[index].total_num
        if (this.list[index].checkNum < totalNum) {
          this.list[index].checkNum++
        }
      }
    },
    // 减数量
    mdMin(index, skuIndex) {
      if (skuIndex || skuIndex == 0) {
        if (this.list[index].sku_list[skuIndex].checkNum > 0) {
          this.list[index].sku_list[skuIndex].checkNum--
        }
      } else {
        if (this.list[index].checkNum > 0) {
          this.list[index].checkNum--
        }
      }
    },

    // 立即发货
    OnBuy(itemID, value, skuName, index, skuIndex) {
      this.buyItemId = itemID
      this.buySkuId = value
      this.buySkuName = skuName
      if (skuIndex || skuIndex == 0) {
        this.buyNum = this.list[index].sku_list[skuIndex].checkNum
      } else {
        this.buyNum = this.list[index].checkNum
      }
      if (!this.isNumber(Number(this.num))) {
        this.$Error('购买的商品数量有误！')
        return
      }
      if (this.buyNum < 1) {
        this.$Error('购买的商品数量不能小于1')
        return
      }
      const orderBuy = {}
      // 跳转到结算
      orderBuy.order_extry = {}
      orderBuy.order_extry.item_date = ''
      orderBuy.order_extry.item_memo = ''
      orderBuy.is_store_serve = ''
      orderBuy.scanCode = ''
      orderBuy.addressId = ''
      orderBuy.order_source = ''
      orderBuy.live_id = ''
      orderBuy.item_id = itemID
      orderBuy.checkbox = ''
      orderBuy.num = this.buyNum
      orderBuy.sku = value
      orderBuy.sku_name = skuName
      orderBuy.assort_id = ''
      orderBuy.total_num = ''
      orderBuy.type = 'onbuy'
      orderBuy.is_dhs_send = 1
      Store.save('orderBuy', orderBuy)
        this.$JumpName(this, 'buy')
    },
    // $_yj转移虚拟库存
    sendVirtual(lowerId, itemID, value, skuName, index, skuIndex) {
      // this.show = true
      Dialog.confirm({
        title: '标题',
        message: '操作调拨库存前，请确认您已经线下收款。库存调拨操作无法撤回，若造成损失需要由您自己承担，请谨慎操作!'
      })
        .then(() => {
          // on confirm
          if (skuIndex || skuIndex == 0) {
            this.buyNum = this.list[index].sku_list[skuIndex].checkNum
          } else {
            this.buyNum = this.list[index].checkNum
          }
          if (this.buyNum < 1) {
            this.$Error('转移虚拟库存数量不能小于1')
            return false
          }
          const params = {
            lower_id: lowerId,
            item_id: itemID,
            sku_id: value,
            num: this.buyNum
          }
          this.$loadingWrap.show()
          setTimeout(() => {
            this.$loadingWrap.close()
          }, 50000)

          sendVirtualPost(params).then(res => {
            this.$loadingWrap.close()
            if (res.status == 1) {
              this.$Error('转移成功')
              this.init()
              this.is_dz()
            } else {
              this.$Error(res.msg)
              /* this.init()
          this.is_dz() */
            }
          })
        })
        .catch(() => {
          // on cancel
          return
        })
    },
    // 实体库存修改库存数量
    sendVirtualEntity(entityId, itemID, value, skuName, index, skuIndex) {
      if (skuIndex || skuIndex == 0) {
        this.buyNum = this.list[index].sku_list[skuIndex].checkNum
      } else {
        this.buyNum = this.list[index].checkNum
      }
      if (this.buyNum < 1) {
        this.$Error('修改实体库存数量不能小于1')
        return false
      } else if (Number(this.buyNum) >= Number(this.list[index].sku_list[skuIndex].num)) {
        this.$Error(`修改实体库存数量不能大于${this.list[index].sku_list[skuIndex].num}`)
        return false
      }
      // this.show = true
      Dialog.confirm({
        title: '修改实体库存',
        message: '操作调拨库存前，请确认您已经线下收款。库存调拨操作无法撤回，若造成损失需要由您自己承担，请谨慎操作!',
        className: 'sendVirtual'
      })
        .then(() => {
          // on confirm
          const params = {
            entity_id: entityId,
            item_id: itemID,
            num: this.buyNum
          }
          // console.log('params', params, skuIndex)
          this.$loadingWrap.show()
          setTimeout(() => {
            this.$loadingWrap.close()
          }, 50000)

          sendVirtualPostEntity(params).then(res => {
            this.$loadingWrap.close()
            if (res.status == 1) {
              this.list[index].sku_list[skuIndex].num = this.buyNum
              this.$Error('修改成功')
            } else {
              this.$Error(res.msg)
              /* this.init()
          this.is_dz() */
            }
          })
        })
        .catch(() => {
          // on cancel
          return
        })
    },
    // 加入购物车
    addCart(itemID, value, skuName, index, skuIndex) {
      // // console.log(itemID, value, skuName, index, skuIndex)
      if (skuIndex || skuIndex == 0) {
        this.num = this.list[index].sku_list[skuIndex].checkNum
      } else {
        this.num = this.list[index].checkNum
      }
      if (!this.isNumber(Number(this.num))) {
        this.$Error('购买的商品数量有误！')
        return
      }
      if (this.num < 1) {
        this.$Error('购买的商品数量不能小于1')
        return
      }
      const data = {
        id: itemID,
        num: this.num, // 数量
        value: value,
        sku_name: skuName,
        dhs_send: 1
      }
      this.$loadingWrap.show()
      addCart(data).then(res => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          this.$Error('已加入购物车')
        } else {
          this.$Error('添加失败：' + res.msg)
        }
      })
    },

    // 兑换预存款
    dhsDeposit(virtualId, index, skuIndex) {
      if (skuIndex || skuIndex == 0) {
        this.num = this.list[index].sku_list[skuIndex].checkNum
      } else {
        this.num = this.list[index].checkNum
      }
      if (this.num < 1) {
        this.$Error('兑换商品数量不能小于1')
        return
      }
      const data = {
        virtual_id: virtualId,
        num: this.num
      }
      this.$loadingWrap.show()
      setTimeout(() => {
        this.$loadingWrap.close()
      }, 50000)
      depositExchange(data).then(res => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          setTimeout(() => {
            this.$router.go(0)
          }, 1000)
        } else {
          this.$Error(res.msg)
        }
      })
    },

    // 加载更多
    loadMore() {
      const param = Object.assign({ p: this.p }, this.postData, true)
      getMyStore(param)
        .then(res => {
          this.loading = false
          const list = res.data.lists
          if (list.length) {
            this.list = this.list.concat(list)
            this.p++
          } else {
            this.finished = true
          }
        })
        .catch(() => {
          // console.log('aaa')
          this.error = true
        })
    },

    Jump(url, data) {
      this.$JumpPath(this, url, data)
    },
    JumpUrl(url) {
        openPage(url)
    },
    JumpUser() {
        wx.navigateBack({
          delta: 1
        })
    },

    isNumber(obj) {
      return typeof obj === 'number' && !isNaN(obj)
    }

  }
})
</script>

<style lang="scss">
@import "src/styles/mixin";
@import "src/styles/variables";
.myStore{
  .nav {
    background-color: $default;
    .wrapper-nav {
      width: 710px;
      margin: 0 auto;
      overflow: hidden;
      .style2-nav {
        height: 90px;
        background: $default;
        display: flex;
        white-space: nowrap;
        line-height: 90px;
        .link {
          flex: 1;
          position: relative;
          display: inline-block;
          text-align: center;
          font-size: 26px;
          color: #333333;
          // margin-top: -30px;
          &.link2{
            width: 355px;
          }
          &.link3{
            width: 236px;
          }
          &.cur {
            font-size: 28px;
            color: #e80001;
            &::after {
              @include gradient(right, #f20b22, rgba(242, 11, 34, 0.1));
            }
          }
          &:last-child::before {
            width: 0;
          }
          &::after {
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            display: block;
            content: "";
            background: transparent;
            width: 90px;
            height: 6px;
          }
        }
      }
    }
  }
  .top {
    position: relative;
    top: 0;
    left: 0;
    width: 100%;
    line-height: 100px;
    background: #fff;
    text-align: center;
    font-size: 36px;
    .icon-back {
      position: absolute;
      top: 50%;
      left: 20px;
      width: 20px;
      height: 40px;
      transform: translateY(-50%);
      background: url(https://img.wifenxiao.com/h5-wfx/images/user/icon_arrowBack.png) center/cover
      no-repeat;
    }
  }
  .mlist-goods {
    margin: 20px 25px;
    .list-goods {
      background: #fff;
      padding:30px 25px;
      margin-bottom: 20px;
      overflow: hidden;
      border-radius: 20px;
      &:last-child {
        margin-bottom: 0;
      }
      .store-pic {
        float: left;
        width: 180px;
        height: 180px;
        img {
          width: 100%;
          height: 100%;
          border-radius: 10px;
        }
      }
      .store-info {
        float: left;
        height: 180px;
        width: calc(100% - 180px);
        box-sizing: border-box;
        padding-left: 20px;
        h3 {
          @include lineClamp(28px, 36px, 2);
          height: 72px;
        }
        p {
          margin: 30px 0 20px;
          color: #666666;
          .stock-del {
            color: #F30C23;
          }
        }
        .store-pop {
          color: #666666;
          .down-icon {
            width: 16px;
            height: 9px;
            display: inline-block;
            vertical-align: middle;
            background: url(https://img.wifenxiao.com/h5-wfx/images/user/down.png) center/cover no-repeat;
            background-size: 100% auto;
          }
        }
      }
      .pop-content {
        float: left;
        width: 100%;
        .pop-content-detail {
          margin-top: 15px;
          padding: 25px;
          background: #F7F7F7;
          overflow: hidden;
          border-radius: 10px;
          .content-left {
            float: left;
            width: 50%;
            height: 100px;
            text-align: left;
            .pop-content-detail-sku {
              margin-bottom: 10px;
              font-size: 26px;
              line-height: 38px;
            }
            .text-con {
              font-size: 24px;
              color: #666666;
              .stock-del {
                font-size: 28px;
                color: #F30C23;
              }
            }
          }
          .content-right {
            width: 50%;
            text-align: right;
            float: right;
            padding-bottom: 80px;
            position: relative;
          }
          .add-cart {
            i,.md-text {
              display: inline-block;
              text-align: center;
              font-size: 26px;
              vertical-align: top;
            }
            i{
              width: 40px;
              height: 44px;
              position: relative;
              img{
                display:inline;
                width: 22px;
                position: absolute;
                left: 50%;
                top: 50%;
                transform: translate(-50%,-50%);
              }
            }
            .md-text {
              border-radius: 10px;
              background: #ededed;
              border: none;
              line-height: normal;
              width: 76px;
              height: 44px;
              padding: 5px 0;
              color: #333;
            }
            .j-addCart {
              width: 45px;
              height: 37px;
              display: inline-block;
              margin-left: 10px;
              background: url(https://img.wifenxiao.com/h5-wfx/images/user/icon_addcart.png) center/100% 100%
              no-repeat;
            }
          }
          .stroe-sku-btn {
            text-align: right;
            position: absolute;
            bottom: 0;
            right: 0;
            white-space: nowrap;
            .dhs-deposit{
              background-color:transparent;
            }
            .dhs-deposit,
            .shipments {
              display: inline-block;
              height: 50px;
              font-size: 24px;
              margin-left: 15px;
              padding: 0 27px;
              &.btn{
                border-radius: 30px;
              }
            }
          }
        }
      }
    }
  }
}
.dzNum{
  margin-top: 8px;
}
.store {
  position: relative;
}
.store-sn {
  position: absolute;
  left: 160px;
  top: 0;
}
.content-left-code{
  width: 100% !important;
}
.flex-content {
  width: 100%;
  margin-top: 10px;
  display: flex;
  .title{
    width: 140px;
  }
  .content {
    flex: 1;
  }
}
.sendVirtual {
  width: 85%;
  .van-dialog__message--has-title {
    font-size: 28px;
    line-height:50px;
    padding: 40px 20px;
  }
  .van-dialog__footer--buttons {
    // padding: 20px 0;
    view {
      font-size: 28px;
    }
    .van-dialog__confirm {
      padding: 40px
    }
    .van-dialog__cancel{
      padding: 40px
    }
  }
}
</style>
